package com.malbbmsomanager.retailmanagement;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.malbbmsomanager.DM_BBM_InvoiceMenu;
import com.malbbmsomanager.R;
import com.malbbmsomanager.adapter.DM_BBM_List_Adapters;

import android.app.ActionBar;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class DM_BBM_Retailer_Master  extends Activity implements
ActionBar.OnNavigationListener{
	private String DBNAME = "dminvoicemanagerbbm.db";
	private String TOWN_DETAILS = "fTown";
	private String ITEM_DEBTOR = "fDebtor";
	private String RETAILER_SUM = "FRetailScrSum";
	TextView txtHeading;
	SQLiteDatabase mydb;
	String retailerCode;
	EditText myFilterCustomer;
	private DM_BBM_List_Adapters dbHelperCustomer;
	private SimpleCursorAdapter dataAdapterCusomer;
	// action bar
	private ActionBar actionBar;
	public void btnBack(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_BBM_InvoiceMenu.class);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		myIntent.putExtra("TAGID", "SALES");
		startActivityForResult(myIntent, 0);
		finish();
	}

	// DisplayRetailerDetails
	// DisplayTownDetails
	public void DisplayRetailerDetails(View view) {
		Button retailerDet = (Button) view;
		retailerCode = retailerDet.getText().toString();
		updateRetailSum();

		Intent myIntent = new Intent(view.getContext(),
				DM_BBM_Retailer_Info_Main_Tabs.class);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();

	}

	private void updateRetailSum() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues addRetailSum = new ContentValues();
			addRetailSum.put("DebCode", retailerCode);
			addRetailSum.put("SumMerchCode", "");
			addRetailSum.put("retSumaddDate", getCurrentTimeStringCustom()
					.toString());
			mydb.insert(RETAILER_SUM, null, addRetailSum);
		} catch (Exception e) {
		}
		mydb.close();
	}

	public void DisplayTownDetails(View view) {
		Button townDet = (Button) view;
		String townCode = townDet.getText().toString();
		Toast.makeText(getApplicationContext(), "townCode :" + townCode,
				Toast.LENGTH_SHORT).show();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_retailer_master);
		
		
		actionBar = getActionBar();

		// Hide the action bar title
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(false);
		
		txtHeading = (TextView) findViewById(R.id.txtHeading);
		txtHeading.setText("Retailer Master");
		myFilterCustomer = (EditText) findViewById(R.id.dminvfiltercustomer);
		dbHelperCustomer = new DM_BBM_List_Adapters(this);
		dbHelperCustomer.open();
		
		DisplayRetailerList();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		mydb.execSQL("DROP TABLE IF EXISTS FRetailScrSum");
		try {
			mydb.execSQL("create table if not exists "
					+ RETAILER_SUM
					+ "(retsum_id integer primary key autoincrement,DebCode text not null,SumMerchCode text not null,retSumaddDate text not null);");
		} catch (Exception e) {
		}
	}

	private void DisplayRetailerList() {
		// Log.v(TAG, "*******populateCustomerDetailsList*******");
				Cursor cursor = dbHelperCustomer.fetchAllCustommersOrderBy();

				// The desired columns to be bound
				String[] columns = new String[] { DM_BBM_List_Adapters.KEY_CUSNAME,
						DM_BBM_List_Adapters.KEY_CUSCODE ,DM_BBM_List_Adapters.KEY_AREACODE};
				String[] fromtrdes = new String[] { "coldes_1", "coldes_2" , "coldes_3" };
				// the XML defined views which the data will be bound to
				int[] to = new int[] { R.id.retailer, R.id.retailercode, R.id.town };

				// create the adapter using the cursor pointing to the desired data
				// as well as the layout information
				dataAdapterCusomer = new SimpleCursorAdapter(this,
						R.layout.dm_bbm_retailer_master_raw, cursor, columns, to, 0);

				ListView listView = (ListView) findViewById(R.id.dmretailerlist);
				// Assign adapter to ListView
				listView.setAdapter(dataAdapterCusomer);

				myFilterCustomer.addTextChangedListener(new TextWatcher() {

					public void afterTextChanged(Editable s) {
					}

					public void beforeTextChanged(CharSequence s, int start, int count,
							int after) {
					}

					public void onTextChanged(CharSequence s, int start, int before,
							int count) {
						dataAdapterCusomer.getFilter().filter(s.toString());
					}
				});

				dataAdapterCusomer.setFilterQueryProvider(new FilterQueryProvider() {
					public Cursor runQuery(CharSequence constraint) {
						return dbHelperCustomer.fetchAllCustommersByNameOrderBy(constraint
								.toString());
					}
				});
	}

	/*private void DisplayRetailerList() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dmretailerlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2", "coldes_3" };
		int[] totrdes = new int[] { R.id.retailer, R.id.retailercode, R.id.town };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curListRetailer = null;
		try {
			//String query = "SELECT DB.DebCode,DB.DebName,DB.TownCode,TW.TownCode,TW.TownName from fDebtor DB,fTown TW Where DB.TownCode = TW.TownCode";
			String query = "SELECT DebCode, DebName ,AreaCode from fDebtor";
			curListRetailer = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (curListRetailer != null) {
			if (curListRetailer.getCount() > 0) {
				while (curListRetailer.moveToNext()) {
					String strDebCode = curListRetailer.getString(0);
					String strDebName = curListRetailer.getString(1);
					String AreaCode = curListRetailer.getString(2);

					
					 * String retailerDetSum = strDebCode + "/" + strDebName +
					 * "/" + strTownCode + "/" +strTownName;
					 

					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", strDebName);
					maptrdes.put("coldes_2", strDebCode);
					maptrdes.put("coldes_3", AreaCode);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_bbm_retailer_master_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		curListRetailer.close();
		mydb.close();
		// DM_List_Expand_Helper.getListViewSize(lvtypedes);
	}
*/
	private String getCurrentTimeStringCustom() {
		// 2013-10-04 00:00:00.000
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yyyy");
		String date_to_string = ddMMMyyFormat.format(dateNow);
		return date_to_string;
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
		
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_search:
			// search action
			return true;
		case R.id.action_location_found:
			// location found
			LocationFound();
			return true;
		case R.id.action_refresh:
			// refresh
			/*
			 * refreshMenuItem = item; // load the data from server new
			 * SyncData().execute();
			 */
			return true;
		case R.id.action_help:
			// help action
			return true;
		case R.id.action_check_updates:
			// check for updates action
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void LocationFound() {
		// TODO Auto-generated method stub
		Intent i = new Intent(DM_BBM_Retailer_Master.this,
				DM_BBM_InvoiceMenu.class);
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(i);
		finish();
		return;
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_actions, menu);
		return true;
	}

}
